/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');

/*
 *@todo  API08 获取标签
 * */
exports.tags = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  //var fields = Env.I;
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  var act = fields.act;
  var tagId = parseInt(fields.tagid);
  var post = fields.post;
  var keyword = fields.keyword || '';
  var manager = fields.manager;
  var more = fields.more;
  var pagesize = fields.pagesize != undefined ? parseInt(fields.pagesize) : C.pageSize;
  var page = fields.page != undefined ? parseInt(fields.page) : 1;
  var type = parseInt(fields.type);//标签类型 1 系统标签 2 自定义标签 3 水印标签 4 美容标签
  var beginIndex = (page - 1) * pagesize;
  var findFields = [];
  var findVal = [];
  var tags = [];

  if (!(manager && manager == 1 && F.isManager(loginStatus.groupid))) {
    //findFields.push('tagtype in(1,2)');
    if (act == 1 && type != 4) {//非管理员且不是拿美容标签时只取有帖子的标签
      findFields.push('tagcount>0');
    }
  }
  if (keyword) {
    findFields.push('tagtitle LIKE CONCAT("%",?,"%")');
    findVal.push(keyword);
  }
  else {
    if (act == 1 && !tagId && !more) {
      findFields.push('fid=0');
    }
  }
  if (tagId) {//提取下级标签
    findFields.push('fid=?');
    findVal.push(tagId);
  }
  if (type && _.v.isIn(type, [1, 2, 3, 4])) {
    findFields.push('tagtype=?');
    findVal.push(type);
  }
  findFields.push('1=1');
  var orderStr = "";
  if (keyword) {
    orderStr = ' ORDER BY LENGTH(tagtitle),CONVERT(tagtitle USING gbk ) COLLATE gbk_chinese_ci ASC';
    if (manager == 1) {
      orderStr = ' ORDER BY CASE tagtype WHEN 2 THEN 3 WHEN 3 THEN 2 ELSE tagtype END,tagcount DESC';
    }
    tags = yield mysql.query('SELECT tagid, tagtype, tagtitle,tagimg, tagcount FROM mh_tags WHERE ' + findFields.join(' AND ') + orderStr + ' LIMIT 0,50',
      findVal);
  }
  else {
    if (act == 2 && page == 1) { // 判断是APP添加标签时，并且是初始未传递keyword,第一页时。返回后台编辑好的标签列表。
      //var tags= yield mysql.query('SELECT mt.tagid,mt.tagtype,mt.tagtitle,mt.tagimg,mt.tagcount FROM mh_tags mt ' +
      //'JOIN mh_slider ms ON mt.tagid = ms.id WHERE ms.status=1 and ms.sstype=5 and ms.begintime<=UNIX_TIMESTAMP() and (ms.endtime+86400)>=UNIX_TIMESTAMP() ORDER BY sort');
      let brond = yield F.getBrondTagid();

      tags = yield mysql.query('SELECT mt.tagid,mt.tagtype,mt.tagtitle,mt.tagimg,mt.tagcount FROM mh_tags mt ' +
        'WHERE mt.tagid in (' + brond.join() + ') ORDER BY (FIELD(mt.tagid,' + brond.join() + '))');
      //SELECT * FROM mh_tags mt WHERE mt.tagid in (133,2,186,6) ORDER BY (FIELD(mt.tagid,33,2,186,6))

    }
    else {
      findVal.push(beginIndex);
      findVal.push(pagesize);
      //var tags = yield mysql.query('SELECT tagid, tagtype, tagtitle,tagimg, tagcount FROM mh_tags WHERE '+findFields.join(' AND ')+' ORDER BY LENGTH(tagtitle),CONVERT(tagtitle USING gbk ) COLLATE gbk_chinese_ci ASC LIMIT ? ,?', findVal);
      //判断是否发现页标签列表
      //var tags = yield mysql.query('SELECT mt.tagid,mt.tagtype,mt.tagtitle,mt.tagimg,mt.tagcount FROM mh_tags mt JOIN mh_slider ms ON mt.tagid = ms.id WHERE ms.status=1 and ms.sstype=5 and ms.begintime<=UNIX_TIMESTAMP() and (ms.endtime+86400)>=UNIX_TIMESTAMP() ORDER BY sort');
      orderStr = ' ORDER BY tagtype,tagcount DESC';
      if (manager == 1) {
        orderStr = ' ORDER BY CASE tagtype WHEN 2 THEN 3 WHEN 3 THEN 2 ELSE tagtype END,tagcount DESC';
      }
      tags = yield mysql.query('SELECT tagid, tagtype,tagtitle,tagimg, tagcount FROM mh_tags WHERE ' + findFields.join(' AND ') + orderStr + ' LIMIT ?,?',
        findVal);
    }
  }
  if (tags.length == 0) {
    return F.returnMsg(300, '获取系统标签失败', 3);
  }
  for (var i in tags) {
    tags[i]['tagurl'] = F.generateTagUrl(tags[i]['tagimg'], tags[i]['tagid']);
    if (act == 2) {//app端添加标签专用
      delete tags[i]['tagurl'];
      delete tags[i]['tagcount'];
    }
    delete tags[i]['tagimg'];
  }
  if (act == 1) {
    return F.returnMsg(200, '获取系统标签成功', 3, tags);
  }
  else {
    return F.returnMsg(200, '获取系统标签成功', 3, {tags: tags});
  }
};
